<template>
  <div class="app-container">
    <!-- 备件退回 -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline filter">
      <el-form-item label="入库日期">
        <el-date-picker
          v-model="alarmdate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item label="单据编号">
        <el-input
          v-model.number="listQuery.fbillno"
          clearable
          class="filter-item"
          style="width: 200px"
          placeholder="请输入单据编号"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="listQuery.fbillstate"
          class="filter-item"
          style="width: 200px"
          clearable
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in fbillstateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工程师">
        <div style="width: 220px;display:flex;justify-content:flex-end;align-items:center">
          <el-select v-model="listQuery.frequuser" style="display: inline-block;width:200px" clearable filterable class="filter-item" placeholder="请选择工程师">
            <el-option
              v-for="item in getListfrequuser"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
          <i style="display: inline-block;width:20px;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialoguse('search')"/>
        </div>
      </el-form-item>
      <el-form-item>
        <!-- v-permission="['part:partoutHead:read']" -->
        <el-button
          :style="{background:buttonColor.lookup,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleFilter"
        >查找</el-button
        >
        <!-- v-permission="['part:partoutHead:create']" -->
        <el-button
          :style="{background:buttonColor.add,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleCreate"
        >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="tableColor"
      stripe
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding" >
        <template slot-scope="scope">
          <!-- v-permission="['purchase:head:update']" -->
          <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" >
              编辑
            </div>

            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="audit(scope.row)">
              <img src="../../../public/images/examine.png" >
              确认
            </div>

            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="auditDelete(scope.row)">
              <img src="../../../public/images/del.png" >
              作废
            </div>

            <div :style="{color:buttonColor.edit,cursor:'pointer'}" >
              <img src="../../../public/images/print.png" >
              打印
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        :index="indexMethod"
        align="center"
        label="序"
        type="index"
      />
      <el-table-column align="center" label="单据编号" prop="fbillno" width="150" />
      <el-table-column
        :formatter="datetimeFormat"
        width="100"
        align="center"
        label="申请日期"
        prop="frequdate"
      />
      <el-table-column :formatter="formatfrequuser" align="center" label="工程师" prop="frequuser" />
      <el-table-column align="center" label="品项数" prop="fitemcount" />
      <el-table-column align="center" label="总件数" prop="fpiececount" />
      <el-table-column align="center" label="总价" prop="ftotalamt" />
      <el-table-column align="center" label="发货人" prop="fsenduser" />
      <el-table-column
        :formatter="datetimeFormat"
        align="center"
        label="发货日期"
        prop="fsenddate"
      />
      <el-table-column :formatter="fsendtypeFormat" align="center" label="快递类型" prop="fsendtype" />
      <el-table-column align="center" label="快递单号" prop="fsendno" />
      <el-table-column align="center" label="申请状态" prop="fbillstate">
        <template slot-scope="scope">
          <span v-if="scope.row.fbillstate === 1" :style="{ color: buttonColor.itemisconfirmed }">{{
            scope.row.fbillstate |
              statusFilter
          }}</span>
          <span v-else-if="scope.row.fbillstate === 2" :style="{ color: buttonColor.itemconfirmed }">{{
            scope.row.fbillstate | statusFilter
          }}</span>
          <span v-else :style="{ color: buttonColor.iteminvalid }">{{ scope.row.fbillstate | statusFilter }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="auto"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="fbillno">
              <el-input :disabled="true" v-model="dataForm.fbillno" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="申请日期"
              prop="frequdate"
            >
              <el-date-picker v-model="dataForm.frequdate" disabled type="date" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="申请状态"
              prop="fbillstate"
            >
              <el-select
                v-model="dataForm.fbillstate"
                disabled
                class="filter-item"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in fbillstateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="工程师" prop="frequuser">
              <div>
                <el-select v-model="dataForm.frequuser" clearable filterable class="filter-item" placeholder="请选择申请人">
                  <el-option
                    v-for="item in getListfrequuser"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
                <i style="display: inline-block;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialoguse('add')"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货人" prop="frecuser">
              <el-input v-model="dataForm.frecuser" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="收货人电话"
              prop="frectelno"
            >
              <el-input v-model="dataForm.frectelno" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="发货人" prop="fsenduser">
              <el-input v-model="dataForm.fsenduser" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="发货日期"
              prop="fsenddate"
            >
              <el-date-picker v-model="dataForm.fsenddate" type="date" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="快递类型"
              prop="fsendtype"
            >
              <el-select
                v-model="dataForm.fsendtype"
                class="filter-item"
                clearable
              >
                <el-option
                  v-for="item in fsendtypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="快递单号" prop="fsendno">
              <el-input v-model="dataForm.fsendno" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="fexplanation">
              <el-input v-model="dataForm.fexplanation" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <el-tabs type="border-card">
        <el-tab-pane label="备件明细">
          <div class="app-container">
            <!-- 子表查询和其他操作 -->
            <div class="filter-container">
              <el-button
                :style="{background:buttonColor.add ,color:buttonColor.color}"
                round
                size="medium"
                class="filter-item"
                icon="el-icon-edit"
                @click="handleUpdate1"
              >添加</el-button
              >
            </div>

            <!-- 子表查询结果 -->
            <el-table
              v-loading="listLoading"
              :data="dataForm.details"
              :header-cell-style="tableColor"
              stripe
              element-loading-text="正在查询中。。。"
              border
              fit
              highlight-current-row
              height="20vh"
            >
              <el-table-column
                align="center"
                label="序"
                prop="fline"
              />
              <el-table-column align="center" label="备件编号" prop="fpartid" />
              <el-table-column
                :formatter="fpartnameFormat"
                align="center"
                label="备件名称"
                prop="fpartname"
              />
              <el-table-column
                align="center"
                label="机器码/序列号"
                prop="fmacno"
                width="120"
              />
              <el-table-column
                :formatter="formatfspec"
                align="center"
                label="规格"
                prop="fspecifications"
              />
              <el-table-column :formatter="formatfunit" align="center" label="单位" prop="funit" />
              <el-table-column align="center" label="批次号" prop="fbatch" />
              <el-table-column align="center" label="售价" prop="fbuyprice" />
              <el-table-column align="center" label="数量" prop="fqty" />
              <el-table-column align="center" label="合计" prop="ftotamt" />
              <el-table-column align="center" label="备注" prop="fmemo" />
              <el-table-column
                align="center"
                label="操作"
                class-name="small-padding"
              >
                <template slot-scope="scope">
                  <el-button
                    :style="{background:buttonColor.delete,color:buttonColor.color}"
                    round
                    size="small"
                    class="button-margin"
                    @click="handleDelete1(scope.row)"
                  >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
      </el-tab-pane></el-tabs
      >

      <div slot="footer" class="dialog-footer">
        <div v-if="viewFlag==false">
          <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
          <el-button v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
        </div>
        <div v-else>
          <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
          <el-button v-if="dialogStatus == 'create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 子表添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible1"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm1"
        :rules="rules1"
        :model="dataForm1"
        status-icon
        label-position="left"
        label-width="auto"
      >

        <el-row>
          <el-col :span="8">
            <el-form-item label="备件编号" prop="fpartid">
              <div style="display:flex;justify-content:flex-end;align-items:center">
                <el-input v-model="dataForm1.fpartid" style="display: inline-block" />
                <i style="display: inline-block;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialog"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="备件名称"
              prop="fpartname"
            >
              <el-input :disabled="true" v-model="dataForm1.fpartname" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="规格"
              prop="fspecifications"
            >
              <el-input :disabled="true" v-model.number="dataForm1.fspecifications" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="机器码/序列号"
              prop="fmacno"
            >
              <el-input v-model="dataForm1.fmacno" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="fbatch">
              <el-input v-model.number="dataForm1.fbatch" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="funit">
              <el-input :disabled="true" v-model.number="dataForm1.funit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="数量" prop="fqtyData">
              <el-input v-model.number="fqtyData" maxlength="6" onkeyup="this.value=this.value.replace(/[^\d]/g,'');"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售价" prop="fbuypriceData">
              <el-input :disabled="true" v-model="fbuypriceData" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计" prop="ftotamtData">
              <el-input :disabled="true" v-model.number="ftotamtData" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="行号" prop="fline">
              <el-input v-model="dataForm1.fline" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="fmemo">
              <el-input v-model="dataForm1.fmemo" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible1 = false">取消</el-button>
        <el-button :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="addData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 设备搜索弹出框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="searchVisible"
      top="5vh"
      title="搜索"
    >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="备件编号">
          <el-input
            v-model="listQuerySearch.fpartid"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入备件编号"
          />
        </el-form-item>
        <el-form-item label="备件名称">
          <el-input
            v-model="listQuerySearch.fpartname"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入备件名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :style="{background:buttonColor.lookup,color:buttonColor.color}"
            round
            size="medium"
            class="filter-item"
            icon="el-icon-search"
            @click="searchFilter"
          >查找</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoadingSearch"
        :data="searchList"
        :header-cell-style="tableColor"
        stripe
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        height="300"
      >
        <el-table-column align="center" label="备件编号" prop="fpartid" />
        <el-table-column align="center" label="备件名称" prop="fpartname" />
        <!-- <el-table-column align="center" label="规格" prop="fspec" /> -->
        <el-table-column
          align="center"
          label="选择"
          class-name="small-padding"
        >
          <template slot-scope="scope">
            <el-button
              :style="{background:buttonColor.confirm,color:buttonColor.color}"
              round
              size="small"
              class="button-margin"
              @click="searchData(scope.row)"
            >确定</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalSearch > 0"
        :total="totalSearch"
        :page.sync="listQuerySearch.page"
        :limit.sync="listQuerySearch.limit"
        style="padding:14px 10px !important"
        @pagination="getSearchList"
      />
    </el-dialog>
    <!-- 人员搜索弹出框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="searchVisibleuse"
      top="5vh"
      title="搜索"
    >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="人员">
          <el-input
            v-model="listQuerySearchuse.username"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入人员"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :style="{background:buttonColor.lookup,color:buttonColor.color}"
            round
            size="medium"
            class="filter-item"
            icon="el-icon-search"
            @click="searchFilteruse"
          >查找</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoadingSearchuse"
        :data="searchListuse"
        :header-cell-style="tableColor"
        stripe
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        height="300"
      >
        <el-table-column align="center" label="账号" prop="id" />
        <el-table-column align="center" label="人员" prop="username" />
        <el-table-column
          align="center"
          label="选择"
          class-name="small-padding"
        >
          <template slot-scope="scope">
            <el-button
              :style="{background:buttonColor.confirm,color:buttonColor.color}"
              round
              size="small"
              class="button-margin"
              @click="searchDatause(scope.row)"
            >确定</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalSearchuse > 0"
        :total="totalSearchuse"
        :page.sync="listQuerySearchuse.page"
        :limit.sync="listQuerySearchuse.limit"
        style="padding:14px 10px !important"
        @pagination="getSearchListuse"
      />
    </el-dialog>
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}
.el-button + .el-button {
  margin-left: 1px;
}
</style>

<script>
import {
  listpartoutHead,
  createpartoutHead,
  updatepartoutHead,
  deletepartoutHead
} from '@/api/partoutHead'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import { getFbillno, checkBiz, getListArea } from '@/api/area'
import { listpartInfo } from '@/api/partInfo'
import { listAdmin } from '@/api/admin'

const statusMap = {
  1: '未确认',
  2: '已确认',
  8: '已作废'
}

export default {
  name: 'STcPartBack',
  components: { Pagination },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      buttonColor: buttonColor,
      indexs: 1,
      viewFlag: false,
      searchVisibleuse: false,
      searchListuse: null,
      listLoadingSearchuse: true,
      totalSearchuse: 0,
      listQuerySearchuse: {
        page: 1,
        limit: 20,
        fpointName: undefined,
        sort: 'create_time',
        order: 'desc'
      },

      searchFlaguse: '',

      getListfrequuser: [],
      getListfrequuserAll: [],
      selectList: [],
      searchVisible: false,
      searchList: null,
      listLoadingSearch: true,
      totalSearch: 0,
      listQuerySearch: {
        page: 1,
        limit: 20,
        fpartid: undefined,
        fpartname: undefined,
        sort: 'create_time',
        order: 'desc'
      },

      fbuypriceData: 0,
      fqtyData: 1,
      ftotamtData: 0,

      searchListAll: [],
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: null,
      listQuery: {
        page: 1,
        limit: 20,
        frequuser: undefined,
        frequdate: undefined,
        ftakedateStart: undefined,
        ftakedateEnd: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        frecuser: undefined,
        frectelno: undefined,
        fsenduser: undefined,
        fsendtype: undefined,
        fsenddate: undefined,
        fsendno: undefined,
        fbilltype: 2,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        frequuser: undefined,
        frequdate: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        frecuser: undefined,
        frectelno: undefined,
        fsenduser: undefined,
        fsendtype: undefined,
        fsenddate: undefined,
        fsendno: undefined,
        fbilltype: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        details: []
      },
      listTmp: [],
      actionsTmp: [],
      dialogFormVisible1: false,
      dialogStatus1: '',
      dataForm1: {
        fpartid: undefined,
        fpartname: undefined,
        fmacno: undefined,
        fspecifications: undefined,
        funit: undefined,
        fbatch: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        ftotamt: undefined
      },

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        frequuser: [{ required: true, message: '申请人员不能为空' }],
        frequdate: [{ required: true, message: '申请日期不能为空' }],
        fitemcount: [
          {
            type: 'number',
            message: '品项数必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fpiececount: [
          {
            type: 'number',
            message: '总件数必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        ftotalamt: [
          {
            type: 'number',
            message: '总价必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        frecuser: [],
        frectelno: [],
        fsenduser: [],
        fsendtype: [
          {
            type: 'number',
            message: '快递类型必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fsenddate: [],
        fsendno: [],

        fexplanation: [],
        fupddate: [],
        foperator: [],
        fcheckdate: [],
        fcheckuser: [],
        fbillstate: [
          {
            type: 'number',
            message: '单据状态必须为数字值',
            transform: (value) => Number(value)
          }
        ]
      },
      rules1: {
        fline: [
          { required: true, message: '行号不能为空' },
          {
            type: 'number',
            message: '行号必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fpartid: [
          { required: true, message: '备件编号不能为空' },
          {
            type: 'number',
            message: '备件编号必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fmacno: [],
        fbuyprice: [
          { required: true, message: '采购价不能为空' },
          {
            type: 'number',
            message: '采购价必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fqty: [
          { required: true, message: '数量不能为空' },
          {
            type: 'number',
            message: '数量必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        ftotamt: [
          { required: true, message: '合计不能为空' },
          {
            type: 'number',
            message: '合计必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fmemo: []
      },
      fbillstateOptions: [
        { value: 1, label: '未确认' },
        { value: 2, label: '已确认' },
        { value: 8, label: '已作废' }
      ],
      fsendtypeOptions: [
        { value: 1, label: '顺丰' },
        { value: 2, label: '圆通' },
        { value: 3, label: '申通' },
        { value: 4, label: '中通' },
        { value: 5, label: '邮政包裹' }
      ]
    }
  },
  watch: {
    fbuypriceData: function(val) {
      if (this.fqtyData && val) {
        const num = (this.fqtyData * parseFloat(val)).toFixed(2)
        return this.ftotamtData = num
      } else {
        return this.ftotamtData = 0
      }
    },

    fqtyData: function(val) {
      if (this.fqtyData && val) {
        const num = (parseFloat(this.fbuypriceData) * val).toFixed(2)
        return this.ftotamtData = num
      } else {
        return this.ftotamtData = 0
      }
    }

  },
  created() {
    this.alarmdate = [this.parserDate(moment(new Date().setDate(1)).format('YYYY-MM-DD')), new Date()]
    this.getList()
    this.getSearchList()
    // 人员弹出框
    this.getSearchListuse()
    getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
      .then(response => {
        this.getListfrequuser = response.data.data.list
      })
      .catch(() => {
        this.getListfrequuser = []
      })
    getListArea({ flag: 13 })
      .then(response => {
        this.getListfrequuserAll = response.data.data.list
      })
      .catch(() => {
        this.getListfrequuserAll = []
      })
    // 全部备件列表
    listpartInfo()
      .then(response => {
        this.searchListAll = response.data.data.list
      })
      .catch(() => {
        this.searchListAll = []
      })
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    parserDate(date) {
      var t = Date.parse(date)
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, '/')))
      }
    },
    fsendtypeFormat(row) {
      if (this.fsendtypeOptions) {
        for (let i = 0; i < this.fsendtypeOptions.length; i++) {
          if (row.fsendtype === this.fsendtypeOptions[i].value) {
            return this.fsendtypeOptions[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 人员弹出框
    getSearchListuse() {
      this.listLoadingSearchuse = true
      const templ = {
        fsiteNoBelong: this.$store.state.user.fsiteNo,
        page: this.listQuerySearchuse.page,
        limit: this.listQuerySearchuse.limit,
        sort: 'create_time',
        order: 'desc',
        username: this.listQuerySearchuse.username
      }
      listAdmin(templ)
        .then(response => {
          this.searchListuse = response.data.data.list
          this.totalSearchuse = response.data.data.total
          this.listLoadingSearchuse = false
        })
        .catch(() => {
          this.searchListuse = []
          this.totalSearchuse = 0
          this.listLoadingSearchuse = false
        })
    },

    // 人员弹出框
    searchFilteruse() {
      this.listQuerySearchuse.page = 1
      this.getSearchListuse()
    },

    // 人员弹出框
    searchDatause(row) {
      this.searchVisibleuse = false
      if (this.searchFlaguse === 'add') {
        this.dataForm.frequuser = row.id.toString()
      } else {
        this.listQuery.frequuser = row.id.toString()
      }
    },

    // 人员弹出框
    searchDialoguse(data) {
      if (data === 'add') {
        this.searchFlaguse = 'add'
      } else {
        this.searchFlaguse = 'search'
      }
      this.searchVisibleuse = true
    },

    // 人员
    formatfrequuser: function(row, column) {
      if (this.getListfrequuserAll) {
        for (let i = 0; i < this.getListfrequuserAll.length; i++) {
          if (row.frequuser == this.getListfrequuserAll[i].value) {
            return this.getListfrequuserAll[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 备件名称
    fpartnameFormat: function(row, column) {
      if (this.searchListAll.length > 0) {
        for (let i = 0; i < this.searchListAll.length; i++) {
          if (row.fpartid == this.searchListAll[i].fpartid) {
            return this.searchListAll[i].fpartname
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 规格回显
    formatfspec(row) {
      if (this.searchListAll.length > 0) {
        for (let i = 0; i < this.searchListAll.length; i++) {
          if (row.fpartid == this.searchListAll[i].fpartid) {
            return this.searchListAll[i].fspec
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 单位回显
    formatfunit(row) {
      if (this.searchListAll.length > 0) {
        for (let i = 0; i < this.searchListAll.length; i++) {
          if (row.fpartid == this.searchListAll[i].fpartid) {
            return this.searchListAll[i].funit
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 获取搜索列表
    getSearchList() {
      this.listLoadingSearch = true
      listpartInfo(this.listQuerySearch)
        .then(response => {
          this.searchList = response.data.data.list
          this.totalSearch = response.data.data.total
          this.listLoadingSearch = false
        })
        .catch(() => {
          this.searchList = []
          this.totalSearch = 0
          this.listLoadingSearch = false
        })
    },

    searchFilter() {
      this.listQuerySearch.page = 1
      this.getSearchList()
    },

    searchData(row) {
      this.searchVisible = false
      this.dataForm1.fpartid = row.fpartid
      this.dataForm1.fpartname = row.fpartname
      this.dataForm1.fspecifications = row.fspec
      this.dataForm1.funit = row.funit
      this.fbuypriceData = row.fbuyprice
      // this.dataForm1.fmacno = row.fequipmentno
    },

    // 搜索弹出框
    searchDialog() {
      this.searchVisible = true
    },
    formatDate: function(date) {
      if (typeof (date) === 'object') {
        var ym
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        ym = '' + y + m + d
        return ym
      } else {
        return date
      }
    },
    getList() {
      this.listQuery.ftakedateStart = this.alarmdate == null ? null : this.formatDate(this.alarmdate[0])
      this.listQuery.ftakedateEnd = this.alarmdate == null ? null : this.formatDate(this.alarmdate[1])
      this.listLoading = true
      listpartoutHead(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        frequuser: undefined,
        frequdate: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        frecuser: undefined,
        frectelno: undefined,
        fsenduser: undefined,
        fsendtype: undefined,
        fsenddate: undefined,
        fsendno: undefined,
        fbilltype: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        details: []
      }
    },
    handleCreate() {
      this.resetForm()
      // 单据编号
      getFbillno({ flag: 2014 })
        .then((response) => {
          if (response) {
            this.dataForm.fbillno = response.data.data
            this.dialogFormVisible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          }
        })
        .catch(() => {
          this.dataForm.fbillno = ''
        })

      this.dataForm.frequdate = new Date()
      this.dataForm.fsenddate = new Date()
      this.dataForm.fbillstate = 1
      this.dataForm.frequuser = this.$store.state.user.id.toString()
      this.dataForm.fsenduser = this.$store.state.user.name
      if (this.fsendtypeOptions.length > 0) {
        this.dataForm.fsendtype = this.fsendtypeOptions[0].value
      }

      this.dialogStatus = 'create'
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.fbilltype = 2
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          createpartoutHead(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加工程师领用主表成功'
              })
              this.selectList = []
              this.indexs = 1
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    audit(row) {
      this.$confirm('是否确定', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        checkBiz({ pBillNo: this.dataForm.fbillno, pBillState: 2, pBizType: 's_tc_partout_head', pUser: this.$store.state.user.id })
          .then(() => {
            for (const v of this.list) {
              if (v.fbillno === this.dataForm.fbillno) {
                // this.dataForm.fbillstate = 2
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.$notify.success({
              title: '成功',
              message: '确认成功'
            })
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },

    auditDelete(row) {
      this.$confirm('是否确定作废', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        this.dataForm.fbillstate = 8
        updatepartoutHead(this.dataForm, this.$route.query.id)
          .then(() => {
            for (const v of this.list) {
              if (v.fbillno === this.dataForm.fbillno) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.$notify.success({
              title: '成功',
              message: '作废成功'
            })
            this.selectList = []
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    handleUpdate(row) {
      if (row.fbillstate == '1') {
        this.viewFlag = false
      } else {
        this.viewFlag = true
      }
      this.listTmp = row
      this.actionsTmp = []
      row.details.forEach((v) => {
        this.actionsTmp.push(v)
        this.selectList.push(v.fpartid)
      })

      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      var end = row.details[row.details.length - 1]
      this.indexs = end.fline + 1
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updatepartoutHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新工程师领用主表成功'
              })
              this.selectList = []
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除工程师领用主表', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletepartoutHead(row)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除工程师领用主表成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    },

    handleUpdate1() {
      this.dataForm1 = {
        fline: this.indexs,
        fpartid: undefined,
        fpartname: undefined,
        fmacno: undefined,
        fspecifications: undefined,
        funit: undefined,
        fbatch: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        ftotamt: undefined
      }
      this.fbuypriceData = 0,
      this.fqtyData = 1,
      this.ftotamtData = 0,
      this.dialogStatus1 = 'create'
      this.dialogFormVisible1 = true
      this.$nextTick(() => {
        this.$refs['dataForm1'].clearValidate()
      })
    },

    handleDelete1(row) {
      const index = this.dataForm.details.indexOf(row)
      this.dataForm.details.splice(index, 1)
      this.selectList.splice(index, 1)
      // this.dataForm.details.pop(row)
    },
    addData() {
      this.$refs['dataForm1'].validate((valid) => {
        this.dataForm1.fbuyprice = parseFloat(this.fbuypriceData)
        this.dataForm1.fqty = this.fqtyData
        this.dataForm1.ftotamt = parseFloat(this.ftotamtData)
        this.dataForm1.fline = this.indexs
        // 备件是否重复
        const tem = this.selectList.indexOf(Number(this.dataForm1.fpartid))
        if (tem < 0) {
          if (valid) {
            this.dialogFormVisible1 = false
            this.dataForm.details.push(this.dataForm1)
            this.selectList.push(Number(this.dataForm1.fpartid))
            this.indexs++
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '所选设备重复'
          })
          return
        }
      })
    },
    // 弹窗点击关闭前的回调
    handleClose() {
      this.indexs = 1
      this.selectList = []
      this.dialogFormVisible = false
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp
          this.dataForm.details = this.actionsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },
    cancel() {
      this.indexs = 1,
      this.selectList = []
      this.dialogFormVisible = false
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp
          this.dataForm.details = this.actionsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    }
  }
}
</script>
